#include<iostream>
#include"Socket.hpp"
#include"Protocol.hpp"
#include<unistd.h>
#include<cassert>
#include<cstdlib>

void Usage(const std::string& proc)
{
    std::cout << "/n/rUsage: " << proc << " serverip serverport[1024+]\n" << std::endl;
}


int main(int argc,char* argv[])
{
    srand(time(nullptr) ^ getpid());
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);
    
    //创建tcp客户端服务
    Sock sock;
    sock.Socket();
    if(!sock.Connect(serverip,serverport))
    {
        std::cerr << "connct error!!!" << std::endl;
        exit(1);
    } 
    //tcp服务创建成功
    int sockfd = sock.GetSockfd();
    int cnt = 1;
    std::string ops = "+-*/%=^";
    while(cnt <= 10)
    {
        std::cout << "===============第" << cnt << "次测试....., " << "===============" << std::endl;
        int x = rand() % 100 + 1;
        usleep(1234);
        char op = ops[rand() % ops.size()];
        usleep(4444);
        int y = rand() % 100;
        Request req(x,y,op);
        req.DebugPrint();

        //序列化为字符串并加上报头封装
        std::string package;
        req.Serialize(package);
        package = EnHeader(package);

        //发送消息给服务端处理
        write(sockfd,package.c_str(),package.size());
        std::cout << "这是最新的发出去的请求:\n" << package;
        
        //测试客户端发出多份报文，服务器能否处理
        // write(sockfd,package.c_str(),package.size());
        // std::cout << "这是最新的发出去的请求:\n" << package;
        // write(sockfd,package.c_str(),package.size());
        // std::cout << "这是最新的发出去的请求:\n" << package;
        // write(sockfd,package.c_str(),package.size());
        // std::cout << "这是最新的发出去的请求:\n" << package;

        char buffer[128];
        std::string inbuffer_stream;
        ssize_t n = read(sockfd,buffer,sizeof(buffer)-1);
        if(n > 0)
        {
            buffer[n] = 0;
            inbuffer_stream += buffer;
            std::string content;
            bool r = DeHeader(inbuffer_stream,content);
            assert(r);
            Response resp;
            r = resp.DeSerialize(content);
            assert(r);
            resp.DebugPrint();
        }
        std::cout << "=================================================" << std::endl;
        cnt++;
        sleep(1);
    }
    
    return 0;
}